package com.jintian.smart.demo.service;

import cn.idev.excel.FastExcel;
import com.alibaba.fastjson.JSON;
import com.jintian.smart.base.api.demo.constant.CategoryTypeEnum;
import com.jintian.smart.base.api.demo.constant.GoodsStatusEnum;
import com.jintian.smart.base.api.demo.entity.CategoryBaseEntity;
import com.jintian.smart.base.api.demo.entity.GoodsEntity;
import com.jintian.smart.base.api.demo.form.GoodsAddForm;
import com.jintian.smart.base.api.demo.form.GoodsImportForm;
import com.jintian.smart.base.api.demo.form.GoodsQueryForm;
import com.jintian.smart.base.api.demo.form.GoodsUpdateForm;
import com.jintian.smart.base.api.demo.view.GoodsExcelVO;
import com.jintian.smart.base.api.demo.view.GoodsVO;
import com.jintian.smart.base.api.security.constant.DataTracerTypeEnum;
import com.jintian.smart.base.api.security.provider.IDataTracerProvider;
import com.jintian.smart.base.api.system.provider.IDictProvider;
import com.jintian.smart.demo.mapper.GoodsMapper;
import com.jintian.smart.kernel.common.util.SmartBeanUtil;
import com.jintian.smart.kernel.common.util.SmartEnumUtil;
import com.jintian.smart.kernel.core.code.UserErrorCode;
import com.jintian.smart.kernel.core.domain.ResponseDTO;
import com.jintian.smart.kernel.core.exception.SmartException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.beetl.sql.core.page.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品
 */
@Service
@Slf4j
public class GoodsService {
    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private CategoryService categoryService;

    @DubboReference
    private IDataTracerProvider dataTracerProvider;

    @DubboReference
    private IDictProvider dictProvider;

    /**
     * 添加商品
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> add(GoodsAddForm addForm) {
        // 商品校验
        ResponseDTO<String> res = this.checkGoods(addForm);
        if (!res.getOk()) {
            return res;
        }
        GoodsEntity goodsEntity = SmartBeanUtil.copy(addForm, GoodsEntity.class);
        goodsEntity.setDeletedFlag(0);
        goodsMapper.insert(goodsEntity);
        dataTracerProvider.insert(goodsEntity.getGoodsId(), DataTracerTypeEnum.GOODS);
        return ResponseDTO.ok();
    }

    /**
     * 更新商品
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> update(GoodsUpdateForm updateForm) {
        // 商品校验
        ResponseDTO<String> res = this.checkGoods(updateForm);
        if (!res.getOk()) {
            return res;
        }
        GoodsEntity originEntity = goodsMapper.single(updateForm.getGoodsId());
        GoodsEntity goodsEntity = SmartBeanUtil.copy(updateForm, GoodsEntity.class);
        goodsMapper.updateById(goodsEntity);
        dataTracerProvider.update(updateForm.getGoodsId(), DataTracerTypeEnum.GOODS, originEntity, goodsEntity);
        return ResponseDTO.ok();
    }

    /**
     * 添加/更新 商品校验
     */
    private ResponseDTO<String> checkGoods(GoodsAddForm addForm) {
        // 校验类目id
        Long categoryId = addForm.getCategoryId();
        CategoryBaseEntity optional = categoryService.queryCategory(categoryId);
        if (!CategoryTypeEnum.GOODS.equalsValue(optional.getCategoryType())) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST, "商品类目不存在~");
        }

        return ResponseDTO.ok();
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> delete(Long goodsId) {
        GoodsEntity goodsEntity = goodsMapper.single(goodsId);
        if (goodsEntity == null) {
            return ResponseDTO.userErrorParam("商品不存在");
        }

        if (!goodsEntity.getGoodsStatus().equals(GoodsStatusEnum.SELL_OUT.getValue())) {
            return ResponseDTO.userErrorParam("只有售罄的商品才可以删除");
        }

        batchDelete(Collections.singletonList(goodsId));
        dataTracerProvider.batchDelete(Collections.singletonList(goodsId), DataTracerTypeEnum.GOODS);
        return ResponseDTO.ok();
    }

    /**
     * 批量删除
     */
    public ResponseDTO<String> batchDelete(List<Long> goodsIdList) {
        if (CollectionUtils.isEmpty(goodsIdList)) {
            return ResponseDTO.ok();
        }

        goodsMapper.batchUpdateDeleted(goodsIdList, 1);
        return ResponseDTO.ok();
    }


    /**
     * 分页查询
     */
    public ResponseDTO<PageResult<GoodsVO>> query(GoodsQueryForm queryForm) {
        queryForm.setDeletedFlag(0);
        PageResult<GoodsVO> pageResult = goodsMapper.query(queryForm);

        // TODO: 2023/5/23 待完善
//        if (pageResult.getEmptyFlag()) {
//            return ResponseDTO.ok(pageResult);
//        }
        // 查询分类名称
        List<Long> categoryIdList = pageResult.getList().stream().map(GoodsVO::getCategoryId).distinct().collect(Collectors.toList());
        Map<Long, CategoryBaseEntity> categoryMap = categoryService.queryCategoryList(categoryIdList);
        pageResult.getList().forEach(e -> {
            CategoryBaseEntity categoryEntity = categoryMap.get(e.getCategoryId());
            if (categoryEntity != null) {
                e.setCategoryName(categoryEntity.getCategoryName());
            }
        });
        return ResponseDTO.ok(pageResult);
    }

    /**
     * 商品导入
     *
     * @param file 上传文件
     * @return 结果
     */
    public ResponseDTO<String> importGoods(MultipartFile file) {
        List<GoodsImportForm> dataList;
        try {
            dataList = FastExcel.read(file.getInputStream()).head(GoodsImportForm.class)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new SmartException("数据格式存在问题，无法读取");
        }

        if (CollectionUtils.isEmpty(dataList)) {
            return ResponseDTO.userErrorParam("数据为空");
        }

        return ResponseDTO.okMsg("成功导入" + dataList.size() + "条，具体数据为：" + JSON.toJSONString(dataList));
    }

    /**
     * 商品导出
     */
    public List<GoodsExcelVO> getAllGoods() {
        List<GoodsEntity> goodsEntityList = goodsMapper.all();
        String dictCode = "GOODS_PLACE";
        return goodsEntityList.stream().map(e ->
                GoodsExcelVO.builder()
                        .goodsStatus(SmartEnumUtil.getEnumDescByValue(e.getGoodsStatus(), GoodsStatusEnum.class))
                        .categoryName(categoryService.queryCategoryName(e.getCategoryId()))
                        .place(Arrays.stream(e.getPlace().split(",")).map(code -> dictProvider.getDictDataLabel(dictCode, code)).collect(Collectors.joining(",")))
                        .price(e.getPrice())
                        .goodsName(e.getGoodsName())
                        .remark(e.getRemark())
                        .build()
        ).collect(Collectors.toList());
    }
}
